<?php

namespace app\web\controller;

use app\web\service\BusesService;
use app\web\service\HomeService;

class HomeController extends CommonController
{
    public function initialize()
    {
        $this->noCheckTokenAction = ["getHomeData", "qrCode", "getData", "getAddress"];
        parent::initialize();
    }

    public function getHomeData(){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        // 首页的banner
        $homeService = $this->app->invokeClass(HomeService::class, [$this->returnData]);
        $bannerData = $homeService->getIndexBanner();

        // 首页设置项
        $settingData = $homeService->getSetting();

        // 首页的线路菜单
        $lineData = $homeService->getLineMenuInfo();

        // 首页的热门线路
        $service = $this->app->invokeClass(BusesService::class, [$this->returnData, $this->params]);
        $hotLineData = $service->getHotLineByPaint(["page" => 1, "pageSize" => 6]);

        $this->returnData["data"] = ["banner" => $bannerData, "Menu" => $lineData, "hotLine" => $hotLineData["data"]["list"], "settingData" => $settingData];
        return $this->return_result($this->returnData);
    }

    public function getData(){
        $homeService = $this->app->invokeClass(HomeService::class, [$this->returnData]);
        $bannerData = $homeService->getInitialize();
        $this->returnData["data"] = $bannerData;
        return $this->return_result($this->returnData);
    }

    //生成二维码
    public function qrCode(){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if($this->params["url"]) {
            require_once env("extend_path") . "/phpqrcode/phpqrcode.php";
            $this->params["url"] = urldecode($this->params["url"]);
            if(request()->server("IS_SCF")) {
                $temp_file = tempnam(sys_get_temp_dir(), "png"); // 生成临时文件
                \QRcode::png($this->params["url"], $temp_file, QR_ECLEVEL_L, 7);
                $this->returnData["returnResource"] = file_get_contents($temp_file);
                return $this->return_result($this->returnData);
            }else {
                \QRcode::png($this->params["url"]);
            }
        }
        return '';
    }

    public function getAddress(){
        $homeService = $this->app->invokeClass(HomeService::class, [$this->returnData]);
        $this->returnData = $homeService->getAddress($this->params);
        return $this->return_result($this->returnData);
    }
}
